<?php
namespace app\admin\controller;

use app\common\model\AdminIpsModel;
use app\common\model\AdminUserModel;
use app\common\model\AdminUserLogModel;
use app\common\model\AdminMenuModel;
use app\common\model\AdminRoleModel;

/**
 * 管理员控制器
 * @author 贺强
 * @time   2021-06-21 16:52:19
 */
class Admin extends Common
{
    /**
     * 添加管理员账号
     * @author 贺强
     * @time   2018-10-25 14:11:14
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $param = $this->request->post();
            if (empty($param['username']) || empty($param['pwd1']) || empty($param['pwd2']) || empty($param['role_id'])) {
                return ajax('非法参数', 101);
            }
            $has = AdminUserModel::getCount([['is_delete', '=', 0], ['username', '=', $param['username']]]);
            if (!empty($has)) {
                return ajax('该账号已存在', 102);
            }
            $pwd1 = $param['pwd1'];
            $pwd2 = $param['pwd2'];
            if ($pwd1 !== $pwd2) {
                return ajax('两次输入的密码不一致', 103);
            }
            unset($param['pwd1'], $param['pwd2']);
            $param['password'] = get_md5_password($pwd2);
            $param['status'] = 1;
            // 随机头像
            $param['avatar'] = '/static/hplus/img/a' . mt_rand(1, 9) . '.jpg';
            $param['sort'] = 99;
            $param['is_delete'] = 0;
            $param['ctime'] = time();
            $param['mtime'] = 0;
            $param['login_time'] = 0;
            $param['is_ip'] = 0;
            $param['login_ip'] = '';
            // 数据入库
            $res = AdminUserModel::add($param);
            if (!$res) {
                return ajax('添加失败', 401);
            }
            return ajax('添加成功');
        } else {
            $where = [['id', '<>', 1]];
            $roles = $this->getRoles($where);
            return view('add', ['roles' => $roles]);
        }
    }

    /**
     * 设置管理员
     * @author 贺强
     * @time   2018-10-25 14:14:27
     */
    public function operate()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            return ajax('非法参数', 101);
        }
        $type = $this->request->post('type');
        if (empty($type)) {
            return ajax('非法操作', 102);
        }
        if ($type === 'delAll') {
            $field = 'is_delete';
            $value = 1;
            $msg = '删除';
            $res = AdminUserModel::delByWhere([['id', 'in', $ids]]);
            if ($res) {
                return ajax('删除成功');
            }
        } elseif ($type === 'disable' || $type === 'disableAll') {
            $field = 'status';
            $value = 4;
            $msg = '禁用';
        } elseif ($type === 'enable' || $type == 'enableAll') {
            $field = 'status';
            $value = 1;
            $msg = '启用';
        } elseif ($type === 'nipAll' || $type === 'nip') {
            $field = 'is_ip';
            $value = 1;
            $msg = '限制IP';
        } elseif ($type === 'mipAll' || $type === 'mip') {
            $field = 'is_ip';
            $value = 0;
            $msg = '免IP';
        } else {
            return ajax('非法操作', 103);
        }
        $res = AdminUserModel::modify([$field => $value], [['id', 'in', $ids]]);
        if ($res) {
            return ajax($msg . '成功');
        } elseif ($res === false) {
            return ajax($msg . '失败', 401);
        } else {
            return ajax('该账号已' . $msg, 104);
        }
    }

    /**
     * 删除管理员
     * @author 贺强
     * @time   2022/9/8 9:52
     */
    public function del()
    {
        if (!$this->request->isAjax()) {
            $this->error('非法操作');
        }
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $id = $this->request->post('id', '');
        if (empty($id)) {
            return ajax('非法参数', 101);
        }
        $res = AdminUserModel::delById($id);
        if (!$res) {
            return ajax('删除失败', 400);
        }
        return ajax('删除成功');
    }

    /**
     * 添加 IP 白名单
     * @author 贺强
     * @time   2021-09-14 18:35:25
     */
    public function addip()
    {
        if ($this->request->isAjax()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $param = $this->request->post();
            if (empty($param['ip'])) {
                return ajax('IP不能为空', 101);
            }
            $param['ip'] = trim($param['ip']);
            // 插入数据库
            $count = AdminIpsModel::getCount(['ip' => $param['ip']]);
            if ($count) {
                return ajax('此IP已加入白名单', 102);
            }
            if (!empty($param['username'])) {
                AdminIpsModel::delByWhere(['username' => $param['username']]);
            }
            $param['login_time'] = 0;
            $res = AdminIpsModel::add($param);
            if (!$res) {
                return ajax('添加失败', 400);
            }
            return ajax('添加成功');
        }
        $list = AdminIpsModel::getList([['username', '<>', '']], ['distinct username'], '', 'username');
        return view('addip', ['list' => $list]);
    }

    /**
     * 后台 IP 白名单
     * @author 贺强
     * @time   2021-09-14 18:33:29
     */
    public function ips()
    {
        $where = [];
        $keyword = $this->request->post('keyword', '');
        if (!empty($keyword)) {
            $where[] = ['ip', 'like', "%{$keyword}%"];
        }
        // 分页参数
        $page = intval($this->request->get('page', 1));
        $pagesize = intval($this->request->get('pagesize', env('app.pagesize', 20)));
        $list = AdminIpsModel::getList($where, true, [$page, $pagesize], ['login_time' => 'desc']);
        // print_r($list);exit;
        foreach ($list as &$item) {
            // $item['status_txt'] = '禁用';
            // if ($item['status']) {
            //     $item['status_txt'] = '正常';
            // }
            if (!empty($item['login_time'])) {
                format_datetime($item['login_time']);
            } else {
                $item['login_time'] = 0;
            }
            if (!empty($item['ctime'])) {
                format_datetime($item['ctime']);
            }
        }
        $count = AdminIpsModel::getCount($where);
        $pages = ceil($count / $pagesize);
        return view('ips', ['list' => $list, 'pages' => $pages, 'keyword' => $keyword]);
    }

    /**
     * 操作 IP 白名单
     * @author 贺强
     * @time   2021-09-14 18:36:25
     */
    public function operate_ip()
    {
        if ($this->request->isAjax()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $ids = $this->request->post('ids');
            if (empty($ids)) {
                return ajax('非法参数', 101);
            }
            $type = $this->request->post('type');
            if (empty($type)) {
                return ajax('非法操作', 102);
            }
            $where = [['id', 'in', $ids]];
            if ($type === 'del' || $type === 'delAll') {
                $res = AdminIpsModel::delByWhere($where);
                $msg = '删除';
            } else {
                return ajax('非法操作', 103);
            }
            if ($res) {
                return ajax($msg . '成功');
            } elseif ($res === false) {
                return ajax($msg . '失败', 400);
            } else {
                return ajax('该ip已' . $msg, 104);
            }
        } else {
            return ajax('非法操作', 105);
        }
    }

    /**
     * 修改管理员
     * @author 贺强
     * @time   2018-10-25 14:13:59
     */
    public function edit()
    {
        $admin = $this->admin;
        $t = $this->request->get('t', '');
        $uname = $admin['username'];
        $rid = intval($admin['role_id']);
        if ($this->request->isAjax()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $param = $this->request->post();
            $id = $param['id'];
            $pau = $param['username'];
            if ($rid === 1) {
                $id = $param['id'];
            } elseif ($uname !== $pau) {
                return ajax('非法操作，只能修改自己的账号', 101);
            }
            if ($rid !== 1) {
                unset($param['role_id']);
            }
            $is_pwd = false;
            if (!empty($param['pwd1']) && !empty($param['pwd2'])) {
                $pwd = $param['pwd1'];
                if ($pwd !== $param['pwd2']) {
                    return ajax('再次输入的密码不一致', 103);
                }
                $len = strlen($pwd);
                $s1 = preg_match("/^[1-9]*$/", $pwd);
                $s2 = preg_match("/^[a-z]*$/", $pwd);
                $s3 = preg_match("/^[A-Z]*$/", $pwd);
                if ($uname !== 'admin' && ($len < 6 || $s1 || $s2 || $s3)) {
                    return ajax('密码不能少于6位，且不能为全数字，全小写，全大写', 102);
                }
                $param['password'] = get_md5_password($pwd);
                // 重新登录
                $is_pwd = true;
            }
            unset($param['pwd1'], $param['pwd2'], $param['username']);
            // 执行修改
            $res = AdminUserModel::modify($param, ['id' => $id]);
            if (!$res) {
                return ajax('修改失败', 400);
            }
            $msg = '修改成功';
            if ($is_pwd && ($uname !== 'admin' || $uname === $pau)) {
                $msg = '密码重置成功，请重新登录';
            }
            return ajax($msg);
        }
        $id = $this->request->get('id');
        if (empty($id)) {
            $id = $admin['id'];
        }
        $user = AdminUserModel::getModel(['id' => $id], true, '', 0);
        if (empty($user)) {
            $this->error('用户不存在');
        }
        if ($user['status'] === 1) {
            $user['status_txt'] = '正常';
        } elseif ($user['status'] === 4) {
            $user['status_txt'] = '禁用';
        } else {
            $user['status_txt'] = '';
        }
        $role_w = [];
        if ($admin['role_id'] !== '1') {
            $role_w = [['id', '<>', 1]];
        }
        $roles = $this->getRoles($role_w);
        $roleArr = array_column($roles, 'role_name', 'id');
        $role_name = $roleArr[$user['role_id']] ?? '';
        return view('edit', compact('admin', 'user', 'roles', 'role_name', 't'));
    }

    /**
     * 管理员列表
     * @author 贺强
     * @time   2018-10-25 14:14:10
     */
    public function lists()
    {
        $where = [['is_delete', '=', 0], ['username', '<>', 'admin']];
        $param = $this->request->get();
        //print_r($param);exit;
        if (!empty($param['keyword'])) {
            $where[] = ['username', 'like', "%{$param['keyword']}%"];
        } else {
            $param['keyword'] = '';
        }
        if (!empty($param['type'])) {
            $where[] = ['role_id', '=', $param['type']];
        } else {
            $param['type'] = '';
        }
        //按状态条件搜索
        if (!empty($param['status']) && is_numeric($param['status'])) {
            $where[] = ['status', '=', $param['status']];
        } else {
            $param['status'] = 0;
        }
        // 分页参数
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? env('app.pagesize', 20);
        $list = AdminUserModel::getList($where, true, [$page, $pagesize], ['login_time' => 'desc']);
        // var_dump($list);exit;
        foreach ($list as &$item) {
            $item['status_txt'] = get_admin_status($item['status']);
            if ($item['is_ip']) {
                $item['is_ip_txt'] = '是';
            } else {
                $item['is_ip_txt'] = '否';
            }
            if (!empty($item['login_time'])) {
                format_datetime($item['login_time']);
            }
            if (!empty($item['ctime'])) {
                format_datetime($item['ctime']);
            }
        }
        if ($this->request->isAjax()) {
            return ajax('获取成功', 200, $list);
        }
        $count = AdminUserModel::getCount($where);
        $pages = ceil($count / $pagesize);
        $roles = $this->getRoles([['id', '<>', 1]]);
        $status = [['id' => 1, 'name' => '正常'], ['id' => 4, 'name' => '禁用']];
        $is_ip = AdminMenuModel::getFieldValue('is_hide', ['identity' => 'admin_ips'], '', 0) ? 0 : 1;
        return view('list', compact('list', 'roles', 'status', 'pages', 'is_ip', 'param'));
    }

    /**
     * 管理员操作日志
     * @author 贺强
     * @time   2022/5/27 9:58
     */
    public function logs()
    {
        $where = [];
        $param = $this->request->param();
        if (!empty($param['keyword'])) {
            $where[] = ['username', 'like', "%{$param['keyword']}%"];
        } else {
            $param['keyword'] = '';
        }
        // 分页参数
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? env('app.pagesize', 20);
        $order = ['ctime' => 'desc'];
        if (!empty($param['sort_field']) && !empty($param['sort_type'])) {
            $order = [$param['sort_field'] => $param['sort_type']];
        }
        $list = AdminUserLogModel::getList($where, true, [$page, $pagesize], $order);
        foreach ($list as &$item) {
            format_timestamp($item['login_time'], $item['ctime']);
            $item['tip'] = $item['log'];
            $item['log'] = eSubstr($item['log'], 20, '...');
            if ($item['tip'] === $item['log']) {
                $item['tip'] = '';
            }
        }
        if ($this->request->isAjax()) {
            return $list;
        }
        $count = AdminUserLogModel::getCount($where);
        $pages = ceil($count / $pagesize);
        $is_ip = AdminMenuModel::getFieldValue('is_hide', ['identity' => 'admin_ips']) ? 0 : 1;
        return view('logs', compact('list', 'pages', 'is_ip', 'param', 'count'));
    }

    /**
     * 获取管理员角色
     * @author 贺强
     * @time   2018-10-30 15:16:13
     * @param array $where 查询条件
     * @return array 返回管理员角色
     */
    private function getRoles($where = ['status' => 1])
    {
        $list = AdminRoleModel::getList($where, ['id', 'role_name']);
        return $list;
    }
}
